﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace WebComTest.WebUI.Models.RequestManagers
{
    public class HttpRequest
    {
        private string url { get; set; }

        public HttpRequest(string url)
        {
            this.url = url;
        }

        public HttpResponse DoPostWthAuthetication(string xmlData, string user, string pwd)
        {
            return DoPost(xmlData, user, pwd);
        }

        public HttpResponse DoSimplePost(string xmlData)
        {
            return DoPost(xmlData, null, null);
        }

        private HttpResponse DoPost(string xmlData, string user, string pwd)
        {
            HttpResponse responseData = new HttpResponse();
            try
            {
                byte[] bytes = Encoding.UTF8.GetBytes(xmlData);

                var request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = bytes.Length;

                if (!string.IsNullOrEmpty(user) && !string.IsNullOrEmpty(pwd))
                {
                    request.Authenticate(user, pwd);
                }

                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(bytes, 0, bytes.Length);
                }
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    responseData.StatusCode = response.StatusCode;

                    using (var streamReader = new StreamReader(response.GetResponseStream()))
                    {
                        responseData.Result = streamReader.ReadToEnd();
                    }
                }

            }
            catch (ProtocolViolationException pvex)
            {
                responseData.ErrorMessage = pvex.Message;
            }
            catch (WebException wex)
            {
                responseData.StatusCode = ((System.Net.HttpWebResponse)wex.Response).StatusCode;
                responseData.ErrorMessage = new StreamReader(wex.Response.GetResponseStream()).ReadToEnd();
            }
            catch (InvalidOperationException ioex)
            {
                responseData.ErrorMessage = ioex.Message;
            }
            catch (NotSupportedException nsex)
            {
                responseData.ErrorMessage = nsex.Message;
            }
            catch (Exception ex)
            {
                responseData.ErrorMessage = ex.Message;
            }
            return responseData;
        }
    }
}